package com.imooc.town.service.impl;

import com.imooc.town.dto.OrderDTO;
import com.imooc.town.enums.ResultEnum;
import com.imooc.town.exception.SellException;
import com.imooc.town.reponsitory.OrderMasterReponsitory;
import com.imooc.town.service.BuyerService;
import com.imooc.town.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * create by song on 2018/3/22
 * To change this template use File | Settings | File Templates.
 */

@Service
@Slf4j
public class BuyerServiceImpl implements BuyerService {

    @Autowired
    private OrderService orderService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderId) {
        OrderDTO orderDTO = this.checkOrderDTO ( openid,orderId );
            return orderDTO;
    }



    @Override
    public OrderDTO cancleOrder(String openId, String orderId) {
        OrderDTO orderDTO = this.checkOrderDTO ( openId,orderId );
        if (orderDTO == null){
            log.error ( "【取消订单】查不到该订单，orderid{}",orderId );
            throw new SellException ( ResultEnum.ORDER_NOT_EXIST );
        }
        return orderService.cancle ( orderDTO );
    }

    private OrderDTO checkOrderDTO(String openid,String orderId){
        OrderDTO orderDTO = orderService.findOne ( orderId );
        if (orderDTO == null){
            return null;
        }
        if (!orderDTO.getBuyerOpenid ().equalsIgnoreCase ( openid )){
            log.error ( "【查询订单】订单的openid不一致,openid{},orderDTO{}",openid,orderDTO );
            throw  new SellException ( ResultEnum.ORDER_OWNER_ERROR );
        }
        return orderDTO;

    }
}
